<template>
  <div class="search">
    <input
      class="search-input"
      v-model="keyWord"
      type="text"
      placeholder="输入城市名或拼音"
    >
    <div class="search-content" ref="searchList" v-show="keyWord">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="city in list"
          :key="city.id"
          @click="choiceCity(city.name)"
        >{{city.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'city-search',
  props: {
    cities: Object
  },
  data () {
    return {
      keyWord: '',
      timer: null,
      list: []
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    choiceCity (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () {
    if (this.searchListScroll) {
      this.searchListScroll.refresh()
    }
    this.searchListScroll = new Bscroll(this.$refs.searchList)
  },
  watch: {
    keyWord () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWord) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let city in this.cities) {
          this.cities[city].forEach(value => {
            if (value.spell.includes(this.keyWord) || value.name.includes(this.keyWord)) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles'
  .search
    padding 0 .1rem
    height .72rem
    background-color $bgColor
    .search-input
      width 100%
      height .62rem
      box-sizing border-box
      padding 0 .1rem
      line-height .62rem
      text-align center
      border-radius .06rem
      color #666
    .search-content
      overflow hidden
      z-index 1
      position absolute
      top 1.58rem
      left 0
      right 0
      bottom 0
      background-color #eee
      ul
        display block
        overflow hidden
        .search-item
          line-height .62rem
          padding left .2rem
          color #666
          background-color #fff
</style>
